package doveclient

import (
	"bytes"
	"github.com/juju/errors"
	"time"
)

type Watcher struct {
	cnfName    string
	curContent []byte
	interval   time.Duration
	closeCh    chan struct{}
	client     *Client
}

type WatchResp struct {
	Content []byte
	Err     error
}

func NewWatcher(client *Client, cnfName string, interval time.Duration) (*Watcher, error) {
	if client == nil {
		return nil, errors.New("client is nil ")
	}

	return &Watcher{
		cnfName:  cnfName,
		interval: interval,
		closeCh:  make(chan struct{}),
		client:   client,
	}, nil
}

func (w *Watcher) Start() chan *WatchResp {
	ch := make(chan *WatchResp)
	f := func() {
		t, err := w.client.GetDoveConfig(w.cnfName)
		if err != nil {
			ch <- &WatchResp{
				Err: err,
			}
			return
		}

		if !bytes.Equal(t, w.curContent) {
			ch <- &WatchResp{
				Content: t,
			}
			w.curContent = t
			return
		}
	}

	go func() {

		f()

		ticker := time.NewTicker(w.interval)
		defer ticker.Stop()

		for {
			select {
			case <-ticker.C:
				f()

			case <-w.closeCh:
				close(ch)
				return
			}
		}
	}()

	return ch
}

func (w *Watcher) Stop() {
	close(w.closeCh)
}
